﻿using System;
using Mbs.ComponentModel.Container;
using Mbs.Reflection;
using ExternalInstanceActivator = Castle.MicroKernel.ComponentActivator.ExternalInstanceActivator;

namespace Mbs.CastleContainer
{
    /// <summary>
    /// 组件生命周期拦截装备
    /// </summary>
    [Serializable]
    public class LifecycleStrategyFacility : MbsFacility
    {
        //private List<ILifecycleListner> Listners = new List<ILifecycleListner>();
        private LifecycleListnerManager ListnerManager = new LifecycleListnerManager();

        public LifecycleStrategyFacility() : base(
            KernelListnerType.ComponentModelCreated
            | KernelListnerType.ComponentCreated
            | KernelListnerType.ComponentDestroyed
            ) { }

        protected override void Init()
        {
            if (Kernel != null)
            {
                IClassLoader classLoader = Kernel.Resolve<IClassLoader>();
                foreach (var item in FacilityConfig.Children)
                    ListnerManager.Register(classLoader.NewInstance<ILifecycleListner>(item.Value));
            }
        }
		
        
        public override void OnComponentModelCreated(Castle.Core.ComponentModel model)
        {
            var instance = model.ExtendedProperties["instance"];

            if (instance != null && model.CustomComponentActivator.Equals(typeof(ExternalInstanceActivator)))
                OnCreated(instance);
        }

        public override void OnComponentCreated(Castle.Core.ComponentModel model, object instance)
        {
            OnCreated(instance);
        }

        public override void OnComponentDestroyed(Castle.Core.ComponentModel model, object instance)
        {
            OnDestroyed(instance);
        }
      
        protected virtual void OnCreated(object item)
        {

            if (item != null)
                ListnerManager.Foreach(listner => listner.OnCreated(item));
        }

        protected virtual void OnDestroyed(object item)
        {
            if (item != null)
                ListnerManager.Foreach(listner => listner.OnDestroyed(item));
        }

        public override void Dispose()
        {
            if (Kernel != null)
                Kernel.ListnerManager.UnRegister(this);

            ListnerManager.Dispose();
        }
    }
}
